//
//  webViewController.m
//  Focus
//
//  Created by dlios on 14-10-29.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//
#define kWinSize [UIScreen mainScreen].bounds.size
#import "webViewController.h"
#import "AFNetworking.h"
#import "recommendController.h"
#import "moreRemarkController.h"
#import <Comment/Comment.h>
#import "YcKeyBoardView.h"
#import "MBProgressHUD.h"
#import "LTBounceSheet.h"
#define color [UIColor colorWithRed:0/255.0 green:175/255.0 blue:240/255.0 alpha:1]
#define color1 [UIColor colorWithRed:255 green:255 blue:255 alpha:1]]
#define color2 [UIColor colorWithRed:226/255.0 green:44/255.0 blue:56/255.0 alpha:1.0]]

@interface webViewController ()<YcKeyBoardViewDelegate>
@property (nonatomic,strong)YcKeyBoardView *key;
@property (nonatomic,assign) CGFloat keyBoardHeight;
@property (nonatomic,assign) CGRect originalKey;
@property (nonatomic,assign) CGRect originalText;
@property(nonatomic,strong) LTBounceSheet *sheet;

@end

@implementation webViewController
-(void)dealloc{
    [super dealloc];
    [_night release];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center addObserver:self selector:@selector(changeBackGroundColor:) name:@"color" object:nil];
        //单例初始化
        _night = [night nightState];

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //隐藏tab
    self.tabBarController.tabBar.hidden = YES;
    //隐藏nav
    //    self.navigationController.navigationBar.hidden = YES;
#pragma mark -
#pragma mark - 导航栏左边button
    UIButton *left = [UIButton buttonWithType:UIButtonTypeCustom];
    left.frame = CGRectMake(0, 0, 40, 40);
    [left setImage:[UIImage imageNamed:@"back.png"] forState:UIControlStateNormal];
    [left addTarget:self action:@selector(leftButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]initWithCustomView:left]autorelease];
    //隐藏导航栏
    //    self.navigationController.navigationBarHidden = YES;
    
#pragma mark -
#pragma mark - 创建webView
    [self creatWebView];
}


#pragma mark -
#pragma mark - 左边button点击事件
-(void)leftButtonAction:(UIBarButtonItem *)sender{
    
    [self.navigationController popToRootViewControllerAnimated:YES];
    
    
}



#pragma mark -
#pragma mark - 创建webView等多种视图
-(void)creatWebView{
    //创建webView
    self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
    //设置不反弹
    //       self.webView.scrollView.bounces = NO;
    
    if (self.integer  == 0) {
        NSURL *url = [NSURL URLWithString:self.recommend.weburl];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [self.webView loadRequest:request];
    } else if (self.integer == 1) {
        NSURL *url = [NSURL URLWithString:self.url];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
        [self.webView loadRequest:request];
        
        self.integer = 0;
        
    }
    
    
    
    self.webView.delegate = self;
    //    self.webView.scrollView.delegate = self;
    //设置不让webView回弹
    self.webView.scrollView.bounces = NO;
    //自动缩放页面以适应屏幕
    [self.webView setScalesPageToFit:YES];
    [self.view addSubview:self.webView];
    [self.webView reload];
    [self.webView setUserInteractionEnabled:YES];
    //创建view1铺满整个视图
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 400, 320, 150)];
    view1.alpha = 0.1;
    view1.backgroundColor = [UIColor clearColor];
    [self.webView addSubview:view1];
    [view1 release];
    //添加下滑清扫手势
    UISwipeGestureRecognizer *swip = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipAction:)];
    swip.direction = UISwipeGestureRecognizerDirectionDown;
    [view1 addGestureRecognizer:swip];
    [swip release];
    //新建上边的view遮盖效果
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    view.backgroundColor = [UIColor whiteColor];
    //创建view上的label显示传过来的标题
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(20, 10, 320, 44)];
    title.text = self.recommend.title;
    title.font = [UIFont systemFontOfSize:14];
    title.textColor = [UIColor blackColor];
    [view addSubview:title];
    [self.webView addSubview:view];
    [view release];
    [title release];
    //sheet上加点击手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [self.webView addGestureRecognizer:tap];
    [tap release];
    
    //创建底下的5个buttond的View
    UIView *downView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height - 48, 320, 80)];
    self.downView = downView;
    [downView release];
    _downView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_downView];
    //创建返回按钮
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [back setBackgroundImage:[UIImage imageNamed:@"circle_icon_quit.png"] forState:UIControlStateNormal];
    back.frame = CGRectMake(10, 10, 32, 32);
    [back addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [_downView addSubview:back];
    //创建分享按钮
    UIButton *share = [UIButton buttonWithType:UIButtonTypeCustom];
    [share setBackgroundImage:[UIImage imageNamed:@"common_icon_share.png"] forState:UIControlStateNormal];
    share.frame = CGRectMake(74, 10, 32, 32);
    [share addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    [_downView addSubview:share];
    //创建查看更多评论按钮
    UIButton *seeRemark = [UIButton buttonWithType:UIButtonTypeCustom];
    [seeRemark setBackgroundImage:[UIImage imageNamed:@"circle_icon_comment.png"] forState:UIControlStateNormal];
    seeRemark.frame = CGRectMake(138, 15, 25, 25);
    [seeRemark addTarget:self action:@selector(seeRemarkAction:) forControlEvents:UIControlEventTouchUpInside];
    [_downView addSubview:seeRemark];
    //创建查看更多评论上面的显示个数label
    UILabel *count = [[UILabel alloc]initWithFrame:CGRectMake(150, 10, 15, 15)];
    self.count = count;
    [count release];
    _count.backgroundColor = [UIColor redColor];
    _count.layer.cornerRadius = 7.5;
    _count.textAlignment = NSTextAlignmentCenter;
    _count.font = [UIFont systemFontOfSize:12];
    _count.text = [NSString stringWithFormat:@"%d", self.Array.count];
    
    _count.clipsToBounds = YES;
    [_downView addSubview:_count];
    [_count release];
    //创建评论按钮
    UIButton *remark = [UIButton buttonWithType:UIButtonTypeCustom];
    [remark setBackgroundImage:[UIImage imageNamed:@"common_icon_pencil_square.png"] forState:UIControlStateNormal];
    remark.frame = CGRectMake(202, 10, 32, 32);
    [remark addTarget:self action:@selector(remarkAction:) forControlEvents:UIControlEventTouchUpInside];
    [_downView addSubview:remark];
    //创建改设置按钮
    UIButton *change = [UIButton buttonWithType:UIButtonTypeCustom];
    [change setBackgroundImage:[UIImage imageNamed:@"common_icon_more.png"] forState:UIControlStateNormal];
    change.frame = CGRectMake(266, 10, 32, 32);
    [change addTarget:self action:@selector(toggle:) forControlEvents:UIControlEventTouchUpInside];
    [_downView addSubview:change];
    [_downView release];
    
    
}

#pragma mark -
#pragma mark - loadButton点击事件
-(void)loadAction:(UIButton *)sender{
    
}
#pragma mark -
#pragma mark - back点击事件
-(void)backAction:(UIButton *)sender{
    
    [self dismissViewControllerAnimated:YES completion:^{
        //写动画等
        
        
    }];
    NSLog(@"sdad");
}
#pragma mark -
#pragma mark - share点击事件
-(void)shareAction:(UIButton *)sender{
    id<ISSContent> content = [ShareSDK content:@"要分享的内容" defaultContent:@"要分享的内容为空时候" image:nil title:@"biaoti" url:@"http:www.rewr.com" description:@"zhe shi miaoshu" mediaType:SSPublishContentMediaTypeNews];
    
    [ShareSDK showShareActionSheet:nil shareList:nil content:content statusBarTips:YES authOptions:nil shareOptions:nil result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
        if (state == SSResponseStateSuccess) {
            NSLog(@"fenxiang cheng gong");
        } else if (state == SSResponseStateFail) {
            NSLog(@"fenxiang shibai le");
        }
    }];
}
#pragma mark -
#pragma mark - seeRemark点击事件
-(void) seeRemarkAction:(UIButton *)sender{
    moreRemarkController *remark = [[moreRemarkController alloc]init];
    remark.delegate = self;
    remark.pk = self.pk;
    remark.recomend = self.recommend;
    remark.i = self.i;

    [self presentViewController:remark animated:YES completion:^{
        
        
    }];
}
#pragma mark -
#pragma mark - remark点击事件
-(void)remarkAction:(UIButton *)sender{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardHide:) name:UIKeyboardWillHideNotification object:nil];
    if(self.key==nil){
        self.key=[[YcKeyBoardView alloc]initWithFrame:CGRectMake(0, kWinSize.height-44, kWinSize.width, 44)];
    }
    self.key.delegate=self;
    [self.key.textView becomeFirstResponder];
    self.key.textView.returnKeyType=UIReturnKeySend;
    [self.view addSubview:self.key];
    
    
}
#pragma mark -
#pragma mark - change点击事件
-(void)toggle:(UIButton *)sender{
    self.sheet = [[LTBounceSheet alloc]initWithHeight:230 bgColor:color1;
    //创建线条view1
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 60, 320, 1)];
    line.backgroundColor = [UIColor redColor];
    [self.sheet addView:line];
    [line release];
    //创建线条view2
    UIView *line1 = [[UIView alloc]initWithFrame:CGRectMake(0, 110, 320, 1)];
    line1.backgroundColor = [UIColor redColor];
    [self.sheet addView:line1];
    [line1 release];
                  
    //创建夜间模式button
    UIButton *option1 = [self produceButtonWithTitle:@"夜间模式"];
    option1.frame=CGRectMake(20, 20, 100, 30);
    option1.backgroundColor = [UIColor colorWithRed:226/255.0 green:44/255.0 blue:56/255.0 alpha:1.0];
    [self.sheet addView:option1];
                  
    //创建switch按钮
    self.mySwitch = [[UISwitch alloc]initWithFrame:CGRectMake(250, 20, 80, 20)];
                  
    [_mySwitch addTarget:self action:@selector(mySwitchAction:) forControlEvents:UIControlEventValueChanged];
    [self.sheet addView:_mySwitch];
    [_mySwitch release];
                  

//创建屏幕亮度button
    UIButton *option2 = [self produceButtonWithTitle:@"百变皮肤"];
    option2.backgroundColor = [UIColor colorWithRed:226/255.0 green:44/255.0 blue:56/255.0 alpha:1.0];
    option2.frame = CGRectMake(20, 70, 100, 30);
    [self.sheet addView:option2];
#pragma mark -
#pragma mark - 创建皮肤变换按钮
    UIButton *redButton = [UIButton buttonWithType:UIButtonTypeCustom];
    redButton.frame = CGRectMake(150, 70, 30, 30);
    redButton.backgroundColor = [UIColor colorWithRed:226/255.0 green:44/255.0 blue:56/255.0 alpha:1.0];
    [redButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.sheet addView:redButton];
                  
    UIButton *blackButton = [UIButton buttonWithType:UIButtonTypeCustom];
    blackButton.frame = CGRectMake(190, 70, 30, 30);
    blackButton.backgroundColor = [UIColor blackColor];
    [blackButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.sheet addView:blackButton];
                  
    UIButton *blueButton = [UIButton buttonWithType:UIButtonTypeCustom];
    blueButton.frame = CGRectMake(230, 70, 30, 30);
    blueButton.backgroundColor = [UIColor colorWithRed:0/255.0 green:175/255.0 blue:240/255.0 alpha:1];
    [blueButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.sheet addView:blueButton];
                  
    UIButton *pinkButton = [UIButton buttonWithType:UIButtonTypeCustom];
    pinkButton.frame = CGRectMake(270, 70, 30, 30);
    pinkButton.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:128/255.0 blue:255/255.0 alpha:1.0];
    [pinkButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.sheet addView:pinkButton];
                  
                  
                  
    //创建字体大小button
    UIButton *option3 = [self produceButtonWithTitle:@"调节字体大小"];
    option3.frame = CGRectMake(20, 120, 100, 30);
    option3.backgroundColor = [UIColor colorWithRed:226/255.0 green:44/255.0 blue:56/255.0 alpha:1.0];
    [self.sheet addView:option3];
    //创建字体大小segment
    NSArray *name = [NSArray arrayWithObjects:@"小",@"中",@"大",@"特大", nil];
    UISegmentedControl *seg = [[UISegmentedControl alloc]initWithItems:name];
    seg.selectedSegmentIndex = 0;
    seg.frame = CGRectMake(150, 120, 150, 30);
    seg.tintColor = [UIColor whiteColor];
    seg.backgroundColor = [UIColor colorWithRed:226/255.0 green:44/255.0 blue:56/255.0 alpha:1.0];
    [seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    [self.sheet addView:seg];
    [self.webView addSubview:self.sheet];
    [self.sheet toggle];
    }
#pragma mark -
#pragma mark - 换肤按钮点击事件
-(void)buttonAction:(UIButton *)sender{
                      
    UIColor *mycolor = sender.backgroundColor;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"color1" object:mycolor];
                      
}
#pragma mark -
#pragma mark -夜间模式switch点击事件
-(void)mySwitchAction:(UISwitch *)switchAction{
    if (self.mySwitch.on == YES) {
    [night nightState].openStatu = 1;
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center postNotificationName:@"Night" object:@"black"];
    [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.img.backgroundColor= 'black'"];
    [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'gray'"];
    [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.backgroundColor= 'black'"];
    _night.openStatu = 1;
    self.view.backgroundColor = [UIColor blackColor];
                          
    }else{
    [night nightState].openStatu = 0;
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center postNotificationName:@"Night" object:@"black"];
    [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.img.backgroundColor= 'white'"];
    [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'black'"];
    [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.backgroundColor= 'white'"];
        _night.openStatu = 0;
                          
        self.view.backgroundColor = [UIColor whiteColor];
            }
    }

#pragma mark -
#pragma mark -字体大小segment点击事件
-(void)segAction:(UISegmentedControl *)seg{
//javascript与webView交互
if (seg.selectedSegmentIndex == 0) {
        NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'";
            [self.webView stringByEvaluatingJavaScriptFromString:str];
                          
        }else if (seg.selectedSegmentIndex == 1){
            NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '110%'";
            [self.webView stringByEvaluatingJavaScriptFromString:str];
        }else if (seg.selectedSegmentIndex == 2){
            NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '120%'";
        [self.webView stringByEvaluatingJavaScriptFromString:str];
        }else{
            NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '130%'";
            [self.webView stringByEvaluatingJavaScriptFromString:str];
    }
        }
#pragma mark -
#pragma mark - 点击手势
-(void)tapAction:(UITapGestureRecognizer *)tap{
                      
    self.sheet.hidden = YES;
                      
                      
}
#pragma mark -
#pragma mark - 清扫下滑手势点击事件
-(void)swipAction:(UISwipeGestureRecognizer *)swip
{
        if (swip.direction == UISwipeGestureRecognizerDirectionDown) {
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
        }
}
#pragma mark -
#pragma mark - 键盘点击显示
                  -(void)keyboardShow:(NSNotification *)note
    {
        CGRect keyBoardRect=[note.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
        CGFloat deltaY=keyBoardRect.size.height;
        self.keyBoardHeight=deltaY;
        [UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
            
            self.key.transform=CGAffineTransformMakeTranslation(0, -deltaY);
        }];
    }
#pragma mark -
#pragma mark - 键盘send取消
                  -(void)keyboardHide:(NSNotification *)note
    {
        [UIView animateWithDuration:[note.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
            
            self.key.transform=CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            
            self.key.textView.text=@"";
            [self.key removeFromSuperview];
        }];
        
    }
#pragma mark -
#pragma mark - 发送回收键盘
                  -(void)keyBoardViewHide:(YcKeyBoardView *)keyBoardView textView:(UITextView *)contentView
    {
        [contentView resignFirstResponder];
        //接口请求
        
    }
#pragma mark -
#pragma mark - 页面将要出现
                  -(void)viewWillAppear:(BOOL)animated{
                      //加载
                      MBProgressHUD *hub = [[MBProgressHUD alloc]initWithView:self.view];
                      hub.labelText = @"加载";
                      [hub setMode:MBProgressHUDModeIndeterminate];
                      [hub show:YES];
                      //多少时间后消失
                      [hub showAnimated:YES whileExecutingBlock:^{
                          float progress = 0.0f;
                          while (progress < 1.0f) {
                              progress += 0.01f;
                              hub.progress = progress;
                              usleep(10000);
                          }
                      } completionBlock:^{
                          [hub removeFromSuperview];
                      }];
                      [self.view addSubview:hub];
                      //创建更改设置空间
                      [super viewDidAppear:YES];
                  }
#pragma mark -
#pragma mark - 给sheet上面的button赋标题,改形状
                  -(UIButton *) produceButtonWithTitle:(NSString*) title
    {
        UIButton * button =[UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor=  [UIColor whiteColor];
        button.layer.cornerRadius=15;
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        button.titleLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14];
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        return button;
    }
                  
#pragma mark - 
#pragma mark - webView将要加载完毕
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    if (_night.openStatu == 1) {
        [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.img.backgroundColor= 'black'"];
        [_webView  stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'gray'"];
        [_webView  stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.backgroundColor= 'black'"];    }
    else{
        [_webView
         stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.backgroundColor= 'white'"];
    }
    

}
#pragma mark - 
#pragma mark - 代理传值协议
                  -(void)sendArrayToWebView:(NSMutableArray *)array{
                      
                      self.Array = (NSMutableArray *)[array count];
                      
                  }
#pragma mark -
#pragma mark - scroll协议
                  //- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
                  //{
                  //    NSLog(@"scrollView %f",scrollView.contentOffset.y);
                  //    if (scrollView.contentOffset.y < 0) {
                  //    [self dismissViewControllerAnimated:YES completion:^{
                  //                              
                  //    }];
                  //}
                  //                      
                  //}
                  
                  - (void)didReceiveMemoryWarning
    {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
                  
    /*
     #pragma mark - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
     {
     // Get the new view controller using [segue destinationViewController].
     // Pass the selected object to the new view controller.
     }
     */
                  
                  @end
